<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="客户姓名" prop="blogNickName">
            <el-input
              v-model="queryParams.blogNickName"
              placeholder="请输入客户姓名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话" prop="mobilePhone">
            <el-input
              v-model="queryParams.mobilePhone"
              placeholder="请输入"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="余额" prop="minBalance">
            <el-input
              v-model="queryParams.minBalance"
              placeholder="请输入"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="global_el_rowStyle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:user:export']">导出</el-button>
      </el-col> -->
    </el-row>
    <el-table :data="manageList" stripe>
      <af-table-column label="会员id" align="left" prop="userId" />
      <af-table-column label="会员编码" align="left" prop="memberCode" />
      <af-table-column
        label="会员推送id"
        show-overflow-tooltip
        align="left"
        prop="blogOpenid"
      />
      <af-table-column label="油企" align="left" prop="enterpriseName" />
      <af-table-column label="来源" align="left" prop="source" />
      <af-table-column label="姓名" align="left" prop="name" />
      <af-table-column label="性别" align="left" prop="sexFlag">
        <template slot-scope="scope">
          <span v-if="scope.row.sexFlag === 'W'">女</span>
          <span v-if="scope.row.sexFlag === 'M'">男</span>
        </template>
      </af-table-column>
      <af-table-column label="生日" align="left" prop="birthday" />
      <af-table-column label="昵称" align="left" prop="blogNickName" />
      <af-table-column label="手机号" align="left" prop="mobilePhone" />
      <af-table-column label="车牌号码" align="left" prop="truckNumber" />
      <af-table-column label="IC卡号" align="left" prop="ICCard" />
      <af-table-column label="电子卡总余额(元)" align="left" prop="balance" />
      <af-table-column label="积分余额" align="left" prop="integral" />
      <af-table-column label="注册时间" align="left" prop="registeDate" />
      <af-table-column label="更新时间" align="left" prop="updateDate" />
      <af-table-column
        label="首次消费的油站"
        align="left"
        prop="firstStationName"
      />
      <af-table-column label="常用油品id" align="left" prop="oilId" sortable />
      <af-table-column label="unid" align="left" prop="unionId" v-if="false" />
      <af-table-column label="操作" align="left" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="orderQuery(scope.row)">
            订单查询
          </el-button>
          <el-button size="mini" type="text" @click="recordQuery(scope.row)">
            充值查询
          </el-button>
          <el-button size="mini" type="text" @click="showBalance(scope.row)">
            余额查询
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.yunhuaUserId === null"
            @click="sendYunHua(scope.row)"
          >
            补充回调
          </el-button>
        </template>
      </af-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="titleOrderInfo"
      :visible.sync="openOrderInfo"
      width="700px"
      append-to-body
    >
      <el-table :data="orderList">
        <af-table-column
          label="油站"
          align="left"
          prop="stationName"
          sortable
        />
        <af-table-column label="订单号" align="left" prop="orderNo" sortable />
        <af-table-column
          label="油品名称"
          align="left"
          prop="oilName"
          sortable
        />
        <af-table-column
          label="油品价格"
          align="left"
          prop="oilPirce"
          sortable
        />
        <af-table-column
          label="加油升数"
          align="left"
          prop="orderLiters"
          sortable
        />
        <af-table-column label="实付金额" align="left" prop="amt" sortable />
        <af-table-column
          label="消费者昵称"
          width="120"
          align="left"
          prop="consumer"
        />
        <af-table-column
          label="加油员"
          width="120"
          align="left"
          prop="oilPersonnel"
        />
        <af-table-column label="加油枪号" align="left" prop="oilGun" />
        <af-table-column
          label="支付类型"
          align="left"
          prop="payType"
          :formatter="payTypeFotmat"
        />
        <af-table-column
          label="油站名称"
          width="120"
          align="left"
          prop="stationName"
          v-if="false"
        />
        <af-table-column
          label="用户id(消费者)"
          align="left"
          prop="consumerId"
          v-if="false"
        />
        <af-table-column
          label="油站id"
          align="left"
          prop="stationId"
          v-if="false"
        />
        <af-table-column
          label="支付完成时间"
          align="left"
          prop="payDate"
          width="160"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.payDate, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </af-table-column>
        <af-table-column
          label="订单创建时间"
          align="left"
          prop="createdDate"
          width="160"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.createdDate, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </af-table-column>
      </el-table>
      <pagination
        v-show="totalOrder > 0"
        :total="totalOrder"
        :page.sync="queryOrder.pageNum"
        :limit.sync="queryOrder.pageSize"
        @pagination="listPage"
      />
    </el-dialog>

    <el-dialog
      :title="titleUseRecord"
      :visible.sync="openUserRecord"
      width="700px"
      append-to-body
    >
      <el-table :data="useRecordList">
        <af-table-column label="油站" align="left" prop="stationName" />
        <af-table-column label="订单号" align="left" prop="orderNo" />
        <af-table-column label="充值金额" align="left" prop="amt" />
        <af-table-column
          label="消费者昵称"
          width="120"
          align="left"
          prop="customerName"
        />
        <af-table-column
          label="充值时间"
          align="left"
          prop="createTime"
        ></af-table-column>
      </el-table>
      <pagination
        v-show="totalOrder > 0"
        :total="totalOrder"
        :page.sync="queryRecord.pageNum"
        :limit.sync="queryRecord.pageSize"
        @pagination="listRecordPage"
      />
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      style=""
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="upload.updateSupport"
          />是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 余额查询 -->
    <el-drawer
      title="余额查询"
      :visible.sync="showBalanceDrawer"
      direction="rtl"
      size="50%"
    >
      <!-- <div v-if="cardUseRangeFlag == 1" style="margin-bottom: 20px;font-size: 24px;">电子卡总余额{{totalBalance}}元</div> -->
      <el-table
        :data="balanceList"
        v-show="!isDetails"
        style="width: 100%"
        :border="true"
        height="500"
      >
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column
          property="cardOilsType"
          label="电子卡类型"
          :formatter="formatterDzkType"
        ></el-table-column>
        <el-table-column
          :property="cardUseRangeFlag === '1' ? 'amt' : 'totalAmt'"
          label="总余额(元)"
        ></el-table-column>
        <el-table-column
          property="recentlyTime"
          label="最后一次变更时间"
          show-overflow-tooltip
        ></el-table-column>
        <af-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="balanceDetails(scope.row)"
              v-if="cardUseRangeFlag === '2'"
            >
              查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleAdjust(scope.row)"
              v-if="cardUseRangeFlag === '1'"
            >
              调整余额
            </el-button>
          </template>
        </af-table-column>
      </el-table>

      <el-table :data="balanceDetailsList" v-show="isDetails" height="500">
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column
          property="cardOilsType"
          label="电子卡类型"
          width="150"
          :formatter="formatterDzkType"
        ></el-table-column>
        <el-table-column
          property="amt"
          show-overflow-tooltip
          label="金额(元)"
          width="200"
        ></el-table-column>
        <el-table-column
          property="stationName"
          show-overflow-tooltip
          label="所属油站"
          width="200"
        ></el-table-column>
        <el-table-column
          property="recentlyTime"
          label="最后一次变更时间"
          width="200"
        ></el-table-column>
        <af-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleAdjust(scope.row)">
              调整余额
            </el-button>
          </template>
        </af-table-column>
      </el-table>
      <el-button
        style="float: right; margin: 15px 10px 0 0"
        v-show="isDetails"
        type="primary"
        @click="isDetails = false"
        >返回</el-button
      >
    </el-drawer>

    <!-- 余额调整弹框 -->
    <el-dialog title="调整余额" :visible.sync="showAdjust" width="40%">
      <el-form
        :model="customerCardChangeDto"
        label-position="top"
        :rules="cardChangeRules"
        ref="adjustRef"
      >
        <el-form-item
          v-if="cardUseRangeFlag === '1'"
          label="油站名称"
          prop="stationId"
          clearable
          size="small"
        >
          <el-select
            v-model="customerCardChangeDto.stationId"
            :clearable="true"
            filterable
            placeholder="请选择油站"
            style="width: 100%"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电子卡总余额(元)">
          <span>99999</span>
        </el-form-item>
        <el-form-item label="调整金额">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="customerCardChangeDto.operateType"
              placeholder="请选择"
              style="width: 130px"
            >
              <el-option label="增加" value="0"> </el-option>
              <el-option label="扣减" value="1"> </el-option>
            </el-select>
            <el-input
              v-model="customerCardChangeDto.amt"
              placeholder="请输入"
              style="flex: 1"
            />
            (元)
          </div>
        </el-form-item>
        <el-form-item label="调整后余额(元)">
          <span>{{ affterAmt }}</span>
        </el-form-item>
        <el-form-item label="赠送优惠券">
          <el-select
            v-model="customerCardChangeDto.couponId"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in couponList"
              :key="item.id"
              :value="item.id"
              :label="item.couponRemark"
            >
              <span style="float: left">{{ item.couponRemark }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                ID:{{ item.id }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否推送消息">
          <el-radio-group v-model="customerCardChangeDto.messagepush">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAdjust = false">取 消</el-button>
        <el-button type="primary" @click="handleAdjustSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listManage,
  getOrderInfo,
  getUseRecord,
  sendToYunHua,
  importTemplate,
  importData,
  cardUserList,
  updateUserRecord,
} from "@/api/customer/manage";
import { stationinfo } from "@/api/station/gun";
import { listPrice } from "@/api/station/price";
import { getToken } from "@/utils/auth";
import { listEnterpriseStation } from "@/api/dept";
import { creationList } from "@/api/coupon/creation";
import { cloneDeep } from "lodash";

export default {
  name: "Customer_Info",
  data() {
    return {
      // 总条数
      total: 0,
      totalOrder: 0,
      // 客户管理表格数据
      manageList: [],
      orderList: [],
      useRecordList: [],
      // 是否显示弹出层
      openOrderInfo: false,
      openUserRecord: false,
      titleOrderInfo: "",
      titleUseRecord: "",
      oilNameOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        minBalance: null,
        customerName: null,
        // commendMan: null,
        // memberGrade: null,
        mobilePhone: null,
        // oilName: null,
        // levelId: this.levelId,
      },
      sendParam: {
        userId: null,
        mobilePhone: null,
      },
      queryOrder: {
        pageNum: 1,
        pageSize: 10,
        oilName: null,
        stationId: null,
        consumerId: null,
      },
      queryRecord: {
        pageNum: 1,
        pageSize: 10,
        stationId: null,
        mobilePhone: null,
        userId: null,
        unionId: null,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/appUserInfo/info/importData",
      },
      balanceList: [],
      showBalanceDrawer: false,
      cardUseRangeFlag: "",
      balanceDetailsList: [],
      isDetails: false,
      totalBalance: 0,
      showAdjust: false,
      customerCardChangeDto: {
        messagepush: "0",
      },
      cardChangeRules: {
        stationId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
        amt: [
          {
            required: true,
            message: "请选择输入调整后的余额",
            trigger: "change",
          },
        ],
      },
      stationList: [],
      couponList: [],
      currentRowData: {}, // 当前
    };
  },
  created() {
    this.getList();
  },
  computed: {
    affterAmt() {
      console.log(111);

      return 333;
    },
  },
  watch: {
    showAdjust(val) {
      if (val) {
        this.getCouPonList();
      }
    },
  },
  methods: {
    handleAdjustSubmit() {
      this.$refs.adjustRef.validate((valid) => {
        if (valid) {
          let customerCardChangeDto = cloneDeep(this.customerCardChangeDto);
          updateUserRecord(customerCardChangeDto).then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.getList();
              this.showAdjust = false;
              this.showBalanceDrawer = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    handleAdjust(row) {
      this.customerCardChangeDto = {};
      this.customerCardChangeDto.id = row.id;
      this.showAdjust = true;
      this.$nextTick(() => {
        this.$refs.adjustRef.clearValidate();
      });
    },
    showBalance(row) {
      this.isDetails = false;
      this.showBalanceDrawer = true;
      this.currentRowData = cloneDeep(row);
      this.getStationList(row.stationId);
      cardUserList({
        enterpriseId: row.stationId,
        mobilePhone: row.mobilePhone,
      }).then((res) => {
        if (res && res.code === 200) {
          this.cardUseRangeFlag = res.data.cardUseRangeFlag;
          if (this.cardUseRangeFlag === "1") {
            this.balanceList = res.data.cardList;
          } else if (this.cardUseRangeFlag === "2") {
            this.balanceList = res.data.cardTypeList;
          }
        } else {
          this.balanceList = [];
        }
      });
    },
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },
    balanceDetails(row) {
      console.log(row.cardList);
      this.balanceDetailsList = row.cardList;
      this.isDetails = true;
    },
    formatterDzkType(row) {
      const types = {
        1: "汽油",
        2: "柴油",
      };
      return types[row.cardOilsType];
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUser(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    payTypeFotmat(row, column) {
      if (row.payType === "sxf") {
        return "随行付";
      } else if (row.payType === "dzk") {
        return "电子卡";
      } else if (row.payType === "wx") {
        return "微信";
      } else if (row.payType === "zfb") {
        return "支付宝";
      } else if (row.payType === "xj") {
        return "现金";
      }
    },
    statusFotmat(row, column) {
      if (row.status === "0") {
        return "未支付";
      } else if (row.status === "1") {
        return "已支付";
      }
    },
    /** 查询客户管理列表 */
    getList() {
      // this.queryParams.levelId = this.levelId

      listManage(this.queryParams).then((response) => {
        this.manageList = response.rows;
        this.total = response.total;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    orderQuery(row) {
      this.queryOrder.consumerId = row.userId;
      this.listPage();
    },
    recordQuery(row) {
      this.queryRecord.userId = row.userId;
      this.queryRecord.mobilePhone = row.mobilePhone;
      this.queryRecord.unionId = row.unionId;
      this.listRecordPage();
    },
    listPage() {
      getOrderInfo(this.queryOrder).then((response) => {
        this.orderList = response.rows;
        this.openOrderInfo = true;
        this.totalOrder = response.total;
        this.titleOrderInfo = "查看客户订单信息";
      });
    },
    listRecordPage() {
      getUseRecord(this.queryRecord).then((response) => {
        this.useRecordList = response.rows;
        this.openUserRecord = true;
        this.totalOrder = response.total;
        this.titleUseRecord = "查看客户充值记录";
      });
    },

    sendYunHua(row) {
      this.sendParam.mobilePhone = row.mobilePhone;
      this.sendParam.userId = row.userId;
      sendToYunHua(this.sendParam).then((response) => {
        if (response.code == 200) {
          this.getList();
        } else {
          throw new Error("");
        }
      });
    },
    // 获取优惠券列表
    async getCouPonList() {
      const res = await creationList({ status: 1 });
      this.couponList = res.rows;
    },
  },
};
</script>
